package com.leetcode.题库;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 覃国强
 * @date 2022-02-26 16:29
 */
public class 题库_0012_整数转罗马数字 {

  public static void main(String[] args) {
    Solution solution = new Solution();
    int num = 27;
    String roman = solution.intToRoman(num);
    System.out.println(roman);
  }

  static
  class Solution {

    static Map<Integer, String> unitMap = new HashMap<>();
    static {
      unitMap.put(1, "I");
      unitMap.put(10, "X");
      unitMap.put(100, "C");
      unitMap.put(1000, "M");
    }

    static Map<String, String> fiveUnitMap = new HashMap<>();
    static {
      fiveUnitMap.put("I", "V");
      fiveUnitMap.put("X", "L");
      fiveUnitMap.put("C", "D");
    }

    static Map<String, String> fourUnitMap = new HashMap<>();
    static {
      fourUnitMap.put("I", "IV");
      fourUnitMap.put("X", "XL");
      fourUnitMap.put("C", "CD");
    }

    static Map<String, String> nineUnitMap = new HashMap<>();
    static {
      nineUnitMap.put("I", "IX");
      nineUnitMap.put("X", "XC");
      nineUnitMap.put("C", "CM");
    }

    public String intToRoman(int num) {
      StringBuilder answerSb = new StringBuilder();
      int base = 1000;
      while (num > 0) {
        int digit = num / base;
        num = num % base;
        String str = digitToRoman(digit, unitMap.get(base));
        answerSb.append(str);
        base /= 10;
      }
      return answerSb.toString();
    }

    private String digitToRoman(int digit, String unit) {
      if (digit == 4) {
        return fourUnitMap.get(unit);
      }
      if (digit == 9) {
        return nineUnitMap.get(unit);
      }
      if (digit < 5) {
        return generateStringForLength(unit, digit);
      }
      return fiveUnitMap.get(unit) + generateStringForLength(unit, digit - 5);
    }

    private String generateStringForLength(String unit, int length) {
      StringBuilder sb = new StringBuilder();
      for (int i = 0; i < length; ++i) {
        sb.append(unit);
      }
      return sb.toString();
    }
  }

}
